package com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl;

import com.iwhalecloud.bss.kite.common.constant.KeyConsts;
import com.iwhalecloud.bss.kite.common.util.KiteBeanUtils;
import com.iwhalecloud.bss.kite.cucc.order.accept.chain.AbstractOrderHandler;
import com.iwhalecloud.bss.kite.cucc.order.util.AcceptUtils;
import com.iwhalecloud.bss.kite.cucc.order.util.AskIdUtils;
import com.iwhalecloud.bss.kite.cucc.order.util.OrderRelUtil;
import com.iwhalecloud.bss.kite.dataservice.entity.inst.IInst;
import com.iwhalecloud.bss.kite.dataservice.entity.order.OrderItemChange;
import com.iwhalecloud.bss.kite.manager.util.ManagerUtils;
import com.iwhalecloud.bss.kite.order.client.dto.InstContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderContainer;
import com.iwhalecloud.bss.kite.order.client.dto.OrderRequest;
import com.iwhalecloud.bss.kite.order.client.proxy.InstContainerProxy;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Component;

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * <Description> <br>
 * 订单受理流程：订单确认
 *
 * @author xiao.xuzhang<br>
 * @version 1.0<br>
 * @taskId <br>
 * @CreateDate 2020年2月12日 <br>
 * @since R9.0<br>
 * @see com.iwhalecloud.bss.kite.cucc.order.accept.chain.impl <br>
 */
@Component
public class OrderConfirmHandler extends AbstractOrderHandler {

    private static final String CUST_ORDER_ID = "custOrderId";
    private static final String ORDER_ITEM_ID = "orderItemId";
    private static final String LAST_ORDER_ITEM_ID = "lastOrderItemId";
    private static final String CHG_ID = "chgId";
    private static final String END_TIME = "endTime";
    private static final String BEG_TIME = "begTime";
    private static final String UPDATE_STAFF = "updateStaff";
    private static final String UPDATE_DATE = "updateDate";

    @Override
    public void doHandle(OrderRequest orderRequest) {
        // 设置同笔订单标识
        AskIdUtils.dealAskId(orderRequest);

        // 设置agreement_id
        OrderRelUtil.setSameFinishAgreementId(orderRequest);

        // 订单关联关系
        OrderRelUtil.setDeriveOderRel(orderRequest);

        // 补充实例公共属性
        setInstCommonInfo(orderRequest);
    }

    /**
     * 补充实例公共属性<br>
     * custOrderId、orderItemId、lastOrderItemId、chgId、endTime、begTime
     * @param orderRequest
     */
    private void setInstCommonInfo(OrderRequest orderRequest) {
        if (Objects.isNull(orderRequest)) {
            return;
        }

        // 对所有订单项变动信息按${tableName_instId}进行分组
        Map<String, List<OrderItemChange>> orderItemChangeMap = OrderContainer.ofRequest(orderRequest)
            .listOrderItemChanges().stream().collect(Collectors.groupingBy(orderItemChange -> {
                return ManagerUtils.join(orderItemChange.getTableName(), orderItemChange.getInstId());
            }));

        Date now = new Date();
        InstContainerProxy instContainer = InstContainer.ofRequest(orderRequest);
        orderItemChangeMap.forEach((key, orderItemChanges) -> {
            if (CollectionUtils.isEmpty(orderItemChanges)) {
                return;
            }

            // 对相同实例的变动信息按时间降序排序(时间最新的排第一)
            orderItemChanges.sort(Comparator.comparing(OrderItemChange::getHandleTime).reversed());
            OrderItemChange orderItemChange = orderItemChanges.get(0);
            IInst inst = instContainer.getInst(orderItemChange.getTableName(), orderItemChange.getInstId());
            if (Objects.isNull(inst)) {
                return;
            }

            // 不是所有实例都包含以下所有属性，属性不存在的，不抛错、不打印日志
            KiteBeanUtils.setValueByName(inst, CUST_ORDER_ID, orderItemChange.getCustOrderId());
            KiteBeanUtils.setValueByName(inst, ORDER_ITEM_ID, orderItemChange.getOrderItemId());
            KiteBeanUtils.setValueByName(inst, LAST_ORDER_ITEM_ID, orderItemChange.getOrderItemId());
            KiteBeanUtils.setValueByName(inst, CHG_ID, orderItemChange.getChgId());
            KiteBeanUtils.setValueByName(inst, END_TIME, KeyConsts.DEFAULT_END_TIME);
            KiteBeanUtils.setValueByName(inst, BEG_TIME, KeyConsts.DEFAULT_BEG_TIME);

            if (!AcceptUtils.isAddInst(inst)) {
                KiteBeanUtils.setValueByName(inst, UPDATE_STAFF, orderRequest.getStaffId());
                KiteBeanUtils.setValueByName(inst, UPDATE_DATE, now);
            }
        });
    }
}
